package android.demo.handler;

import android.demo.BaseActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class HandlerActivityC extends BaseActivity {

	private MyHandler myHandler = null;
	private TextView myTextView = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myTextView = new TextView(this);
		myTextView.setId(100);
		setContentView(myTextView);
		
		Log.i(TAG, "Current Thread ID: " + Thread.currentThread().getId());
		
		//生成一个HandlerThread对象，使用Looper来处理消息队列。
		HandlerThread myThread = new HandlerThread("myThread");
		//启动线程
		myThread.start();
		//将一个线程绑定到myHandler这个对象
		myHandler = new MyHandler(myThread.getLooper());
		//从myHandler这个对象中获取消息
		Message msg = myHandler.obtainMessage();
		//将msg对象发送给目标的Handler
		msg.sendToTarget();

//		//下面制造一个自己的线程
//        MyOwnThread myOwnThread = new MyOwnThread();
//        myOwnThread.start();

	}
	
	public class MyHandler extends Handler {
		
    	public MyHandler() {
    	}
    	
    	public MyHandler(Looper looper){
    		super(looper);
    	}
    	
    	public void handleMessage(Message msg){
    		
    		Log.i(TAG, "Current MyHandle Thread ID: " + Thread.currentThread().getId());
       		int i = 1;
       		
    		while(true) {
    			try {
    				//休眠一段时间
    				Thread.sleep(1000);
    	    		Log.i(TAG, "Current MyHandle Thread ID: " + Thread.currentThread().getId());
    	    		myTextView.setText("text" + i);
    	    		i++;
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}    	
    	}

	}
	
	public class MyOwnThread extends Thread {
		
		//休眠时间
    	int sleepSpan = 2000;
    	// 线程执行标志位
    	boolean flag;

    	public MyOwnThread(){
    		this.flag = true;
    	}
    	
    	@Override
    	public void run(){

    		Looper.prepare();
    		int i = 1;
    		
    		while(flag){
    			try{
    				//休眠一段时间
    				Thread.sleep(sleepSpan);
    				
    	    		Log.i(TAG, "Current MyOwnThread Thread ID: " + Thread.currentThread().getId());
    	    		myTextView.setText(i);
    	    		i++;
    			}
    			catch(Exception e){
    				e.printStackTrace();
    			}
    		}    			
    		Looper.loop();
    	}
	}


}
